#include "node.h"
#include <iostream>

using namespace std;
Node::Node()
{
}

Node::~Node(){
    /*free(m_action);
    free(m_father_node);
    free(m_board);*/
}

Action::Action(int x, int y, int value){
    this->m_piece_x = x;
    this->m_piece_y = y;
    this->value = value;
}

void Node::set_board(ReversiBoard *board){
    this->m_board = board;
}

void Node::set_father_node(Node *father){
    m_father_node = father;
}

void Node::set_parent_action(Action *action){
    m_action = action;
}

void Node::set_role(role role){
    m_player = role;
}

void Node::set_color(player c){
    m_color = c;
}

player Node::get_color(){
    return m_color;
}


ReversiBoard* Node::get_board(){
    return m_board;
}

Node Node::backup(){
    Node backup = Node();

    // color
    if ( this->get_color() == 0){
        backup.set_color(WHITE_PLAYER);
    } else {
        backup.set_color(BLACK_PLAYER);
    }

    // role
    if ( this->get_role() == MAX_PLAYER){
        backup.set_role(MAX_PLAYER);
    } else{
        backup.set_role(MIN_PLAYER);
    }

    // board
    backup.set_board( new ReversiBoard(this->get_color()));
    backup.set_board(this->get_board()->to_array());

    // action
    //backup.m_action->m_piece_x


    return backup;


}

void Node::set_board(int *board){
    ReversiBoard *m_board = new ReversiBoard(this->get_color());
    int count=0;
    for ( int row = 0; row < 8; row++){
        for ( int col = 0; col < 8; col++){
            if ( board[8*row + col] == 1){
                m_board->set_piece(row, col, true);
                count++;
            } else{
                m_board->set_piece(row, col, false);
            }
        }
    }
    m_board->set_score(count);

}

role Node::get_role(){
    return this->m_player;
}

bool Node::is_final(){
    // TODO: tabuleiro incompleto onde a quantidade
    // de peças nao pode mais ser ultrapassada

    // tabuleiro completo
    bool final = false;
    int count = 0;
    for ( int i =0; i < 7; i++){
        for ( int j =0; j < 7; j ++){
            if ( m_board->get_piece(i,j) == 1){
                count++;
            }
        }
    }
    if (count == 64){
        final = true;
    }
    return final;
}

void Node::print(){
    for (int row= 0 ; row < 8; row++){
        for ( int col = 0; col <8 ; col++){
            cout << this->m_board->get_piece(row, col) << " | ";
            if ( col == 7){
                cout << this->m_board->get_piece(row, col);
            }
        }
        cout << endl;
    }

}


void Node::play(Action *action){
    this->get_board();
    if ( m_board != NULL ){
        this->m_board->set_piece(action->m_piece_x, action->m_piece_y, true);
    }

    /*if ( valor == 1){

        this->m_board->set_piece(action->m_piece_x, action->m_piece_y, true);
    } else{
        this->m_board->set_piece(action->m_piece_x, action->m_piece_y, false);
    }*/
}
